#include "events.h"

void panic( char *reason ) {
	perror( reason );
	exit( 111 );
}

void init_log( ) {
	stdpath = malloc( strlen( PREFIX ) + 12 *sizeof( char ) );
	sprintf( stdpath, "%slogs/std.log\0", PREFIX );
	errpath = malloc( strlen( PREFIX ) + 12 *sizeof( char ) );
	sprintf( errpath, "%slogs/err.log\0", PREFIX );
	
	ts = time( NULL );
	tsformat( ftime );
}

void tsformat( ) {
	struct tm *tmp;
	time_t curtime;
	
	time( &curtime );
	tmp = localtime( &curtime );
	
	strftime( ftime, 256, "%D - %T", tmp );
	
	return(0);
}

void log( int type, char *buf ) {
	int nts = time( NULL );
	if( nts != ts ) {
		ts = time( NULL );
		tsformat( );
	}
	
	FILE *fp;
				
	if( type == STD ) {
		if( ( fp = fopen( stdpath, "r+" ) ) == NULL )
			perror( "fopen stdlog file." );
			
		fseek( fp, 0, SEEK_END );
		fprintf( fp, "%s $ %s\n", ftime, buf );
	}
	
	else {
		if( ( fp = fopen( errpath, "r+" ) ) == NULL )
			perror( "fopen errlog file." );
		
		fseek( fp, 0, SEEK_END );	
		fprintf( fp, "%s $ %s\n", ftime, buf );
	}
	
	fclose( fp );
}

